<template>
	<m-button wh="s" :type="isDisable?'disabled':'theme'" :loading="codeLoading" @click="SendCodes" gap="10 34" radius="10">
		<text v-if="timer<=0">{{title}}</text>
		<text v-else>{{timer}}s</text>
	</m-button>
</template>
<script>
	import { email, mobile } from '@/libs/fn/verify.js'
	import { SendCode_Phone, SendCode_Mail } from '@/api/Ctrls.js'
	export default {
		name: "m-sendCode",
		data() {
			return {
				timeObj: '',
				timer: 0,
				codeLoading: false,
			};
		},
		props: {
			type: {
				type: String,
				default: ''
			},
			title: {
				type: String,
				default: '发送'
			},
			isSend: {
				type: Boolean,
				default: false
			},
			value: '',
		},
		computed: {
			isDisable() {
				return this.timer > 0
			},
		},
		methods: {
			async SendCodes() {
				if (this.timer > 0) return
				if (!this.value) {
					return this.Toast('请输入手机号/邮箱')
				}
				this.codeLoading = true;

				// const success = await SendCode_Phone({
				// 	phone: this.value,
				// })

				// this.codeLoading = false;
				// if (success) {
				// 	this.timer = 60;
				// 	this.timeObj = setInterval(() => {
				// 		this.timer--
				// 	}, 1000)
				// }


				const type = mobile(this.value) ? 'phone' : 'mail'
				const meth = {
					'phone': SendCode_Phone,
					'mail': SendCode_Mail
				} [type];
				const params = {
					'phone': {
						username: this.value,
					},
					'mail': {
						username: this.value,
					}
				} [type] || false;
				const success = await meth(params);
				this.codeLoading = false;
				if (success) {
					this.timer = 60;
					this.timeObj = setInterval(() => {
						this.timer--
					}, 1000)
				}
			},
		},
	}
</script>

<style lang="scss">
	.m-button {
		box-sizing: border-box;
		border-radius: 15rpx;
	}
</style>